import React, { useState, useEffect, useContext } from 'react';
import './GradePage.css';
import GradeTable from './components/GradeTable';
import AddEditGradeModal from './components/AddEditGradeModal';
import ConfirmModal from './components/ConfirmModal';
import GradeDetailModal from './components/GradeDetailModal';
import { Grade } from './types';
import { DataContext } from '../../shared/DataContext';
// 尝试导入审计日志函数，如果不存在则创建一个空函数
let addAuditLog: (log: any) => void = () => {};
try {
  // 假设有一个审计日志模块，如果不存在则忽略错误
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const auditModule = require('../../shared/audit');
  addAuditLog = auditModule.addAuditLog || (() => {});
} catch (error) {
  // 模块不存在时的回退处理
  console.log('审计日志模块未找到，将跳过日志记录');
}

const GradePage: React.FC = () => {
  const dataContext = useContext(DataContext);
  
  if (!dataContext) {
    throw new Error('GradePage must be used within a DataProvider');
  }
  
  const {
    classes,
    teachers,
    students,
    getClassById,
    getTeacherById,
    academyOptions,
    stageOptions
  } = dataContext;

  // 教学周期选项 - 一个月为一个教学周期
  const termOptions = [
    { value: '2025.9.22-2025.10.24', label: '2025.9.22-2025.10.24' }
  ];

  // 考试类型选项
  const examTypeOptions = [
    { value: '周考', label: '周考' },
    { value: '月考', label: '月考' }
  ];

  // 科目选项
  const subjectOptions = [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'geography', label: '地理' },
    { value: 'politics', label: '政治' }
  ];

  // 根据班级数据生成班级选项，使用统一的数据结构
  const classOptions = classes.map(cls => ({
    value: cls.id || cls.classId || cls.name, // 支持不同的ID字段名
    label: cls.name || cls.className,
    id: cls.id || cls.classId,
    name: cls.name || cls.className,
    academy: cls.academy,
    stage: cls.stage,
    headTeacherId: cls.headTeacherId,
    studentCount: cls.studentCount
  }));
  
  // 根据学生数据生成学生选项，包含必要的classId和academy字段
  const studentOptions = students.map(student => ({
    value: student.id,
    label: `${student.name} (${student.studentId})`,
    classId: student.classId,
    academy: getClassById(student.classId)?.academy || ''
  }));

  // 根据教师数据生成导员选项
  const instructorOptions = teachers.filter(t => t.role === 'instructor').map(teacher => ({
    value: teacher.name,
    label: teacher.name
  }));

  // 根据教师数据生成讲师选项
  const lecturerOptions = teachers.filter(t => t.role === 'lecturer').map(teacher => ({
    value: teacher.name,
    label: teacher.name
  }));

  // 教学月度选项 - 对应班级管理的阶段
  const teachingMonthOptions = stageOptions.map(stage => ({
    value: stage.value,
    label: stage.label
  }));

  // studentOptions 已经在上面定义，包含了必要的classId和academy字段

  const [grades, setGrades] = useState<Grade[]>([]);
  const [filteredGrades, setFilteredGrades] = useState<Grade[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedTerm, setSelectedTerm] = useState('');
  const [selectedExamType, setSelectedExamType] = useState('');
  const [selectedSubject, setSelectedSubject] = useState('');
  const [showAddEditModal, setShowAddEditModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedGrade, setSelectedGrade] = useState<Grade | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState<Omit<Grade, 'id'>>({
    term: '',
    examType: '',
    studentId: '',
    studentName: '',
    subject: '',
    score: 0,
    remark: '',
    academy: '',
    className: '',
    instructor: '',
    lecturer: '',
    teachingMonth: '',
    totalStudents: 40,
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const itemsPerPageOptions = [5, 10, 20, 50]; // 每页显示条数选项

  // 计算总页数
  const totalPages = Math.ceil(filteredGrades.length / itemsPerPage);

  // 处理每页显示条数变化
  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value, 10));
    setCurrentPage(1); // 重置到第一页
  };

  // 跳转到指定页码
  const handlePageJump = (pageNum: number) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  // 快速跳转到首页或末页
  const goToFirstPage = () => setCurrentPage(1);
  const goToLastPage = () => setCurrentPage(totalPages);

  // 从DataContext获取成绩数据
  useEffect(() => {
    // 确保dataContext中有成绩数据获取方法
    if (dataContext && typeof dataContext.getGrades === 'function') {
      const fetchGrades = async () => {
        try {
          const gradesData = await dataContext.getGrades();
          setGrades(gradesData);
        } catch (error) {
          console.error('Failed to fetch grades:', error);
        }
      };
      fetchGrades();
    } else {
      // 作为后备方案，从localStorage读取成绩数据
      const savedGrades = localStorage.getItem('grades');
      if (savedGrades) {
        try {
          setGrades(JSON.parse(savedGrades));
        } catch (error) {
          console.error('Failed to parse grades from localStorage:', error);
        }
      }
    }
  }, [dataContext]);
  
  // 当选择班级时，自动填充相关信息 - 支持不同的数据结构
  const handleClassChange = (className: string) => {
    // 尝试多种方式查找班级，兼容不同的数据结构
    const selectedClass = classes.find(cls => 
      (cls.id === className || cls.classId === className || cls.name === className || cls.className === className)
    );
    
    if (selectedClass) {
      // 获取导员信息（支持不同的字段名）
      const headTeacher = teachers.find(t => 
        t.id === selectedClass.headTeacherId || 
        (t.role === 'instructor' && t.name === selectedClass.advisorName)
      );
      
      // 获取讲师信息
      const lecturer = teachers.find(t => 
        t.role === 'lecturer' && t.name === selectedClass.lecturerName
      );
      
      // 计算学生人数（如果没有直接提供）
      const calculatedStudentCount = selectedClass.studentCount || 
        students.filter(s => s.classId === selectedClass.id || s.classId === selectedClass.classId).length;
      
      // 更新表单数据
      setFormData(prev => ({
        ...prev,
        academy: selectedClass.academy || '',
        className: selectedClass.name || selectedClass.className || '',
        classId: selectedClass.id || selectedClass.classId,
        instructor: headTeacher?.name || selectedClass.advisorName || '',
        instructorId: headTeacher?.id || selectedClass.headTeacherId,
        lecturer: lecturer?.name || selectedClass.lecturerName || '',
        lecturerId: lecturer?.id,
        teachingMonth: selectedClass.stage || '',
        totalStudents: calculatedStudentCount || 0
      }));
    }
  };

  // 当成绩数据变化时，更新localStorage
  useEffect(() => {
    // 只在成绩数据非空时保存，避免重复保存和存储空间浪费
    if (grades.length > 0) {
      try {
        // 检查localStorage空间是否充足
        const jsonData = JSON.stringify(grades);
        // 简单的空间检查（实际浏览器限制通常为5-10MB）
        if (jsonData.length > 5 * 1024 * 1024) { // 超过5MB警告
          console.warn('成绩数据过大，可能导致localStorage空间不足');
          // 可以考虑只保存最近的数据或压缩数据
          const limitedGrades = grades.slice(0, Math.floor(grades.length * 0.8)); // 只保存80%的数据
          localStorage.setItem('grades', JSON.stringify(limitedGrades));
        } else {
          localStorage.setItem('grades', jsonData);
        }
      } catch (error) {
        console.error('保存成绩数据到localStorage失败:', error);
        // 空间不足时的降级处理
        try {
          // 尝试清除旧数据后重新保存
          localStorage.removeItem('grades');
          localStorage.setItem('grades', JSON.stringify(grades.slice(0, Math.floor(grades.length * 0.5))));
        } catch (retryError) {
          console.error('降级保存也失败:', retryError);
        }
      }
    }
  }, [grades]);

  // 过滤成绩数据
  useEffect(() => {
    let result = [...grades];

    // 按学生姓名、学号搜索
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        grade =>
          grade.studentName.toLowerCase().includes(term) ||
          grade.studentId.toLowerCase().includes(term)
      );
    }

    // 按学期过滤
    if (selectedTerm) {
      result = result.filter(grade => grade.term === selectedTerm);
    }

    // 按考试类型过滤
    if (selectedExamType) {
      result = result.filter(grade => grade.examType === selectedExamType);
    }

    // 按科目过滤
    if (selectedSubject) {
      result = result.filter(grade => grade.subject === selectedSubject);
    }

    // 按成绩降序排序
    result.sort((a, b) => (b.score || 0) - (a.score || 0));

    setFilteredGrades(result);
    setCurrentPage(1); // 重置到第一页
  }, [grades, searchTerm, selectedTerm, selectedExamType, selectedSubject]);

  // 分页逻辑
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentGrades = filteredGrades.slice(indexOfFirstItem, indexOfLastItem);

  // 处理查看成绩详情
  const handleViewDetail = (grade: Grade) => {
    setSelectedGrade(grade);
    setShowDetailModal(true);
  };

  // 处理添加成绩记录
  const handleAddGrade = () => {
    setSelectedGrade(null);
    setIsEditing(false);
    // 使用默认的教学周期
    setFormData({
      term: termOptions[0]?.value || '',
      examType: '',
      studentId: '',
      studentName: '',
      subject: '',
      score: 0,
      remark: '',
      academy: '',
      className: '',
      instructor: '',
      lecturer: '',
      teachingMonth: '',
      totalStudents: 0,
    });
    setShowAddEditModal(true);
  };

  // 处理编辑成绩记录
  const handleEditGrade = (grade: Grade) => {
    setSelectedGrade(grade);
    setIsEditing(true);
    setFormData({
      term: grade.term || termOptions[0]?.value || '',
      examType: grade.examType,
      studentId: grade.studentId,
      studentName: grade.studentName,
      subject: grade.subject,
      score: grade.score,
      remark: grade.remark || '',
      academy: grade.academy || '',
      className: grade.className || '',
      instructor: grade.instructor || '',
      lecturer: grade.lecturer || '',
      teachingMonth: grade.teachingMonth || '',
      totalStudents: grade.totalStudents || 0,
    });
    setShowAddEditModal(true);
  };

  // 确保AddEditGradeModal组件接收到所有必要的选项数据
  const getAddEditModalProps = () => {
    return {
      isOpen: showAddEditModal,
      onClose: () => setShowAddEditModal(false),
      onSave: handleSaveGrade,
      initialData: selectedGrade,
      isEditing: isEditing,
      termOptions,
      examTypeOptions,
      studentOptions,
      subjectOptions,
      academyOptions,
      classOptions,
      instructorOptions,
      lecturerOptions,
      teachingMonthOptions,
      onClassChange: handleClassChange
    };
  };

  // 处理删除成绩记录
  const handleDeleteGrade = (grade: Grade) => {
    setSelectedGrade(grade);
    setShowConfirmModal(true);
  };

  // 确认删除成绩记录
  const confirmDeleteGrade = () => {
    if (selectedGrade) {
      setGrades(grades.filter(g => g.id !== selectedGrade.id));
      setShowConfirmModal(false);
      setSelectedGrade(null);
    }
  };

  // 保存成绩信息（添加或编辑）
  const handleSaveGrade = (gradeData: Grade) => {
    // 确保班级数据的一致性
    const finalGradeData: Grade = {
      ...gradeData,
      // 如果没有提供classId，尝试从班级列表中查找
      classId: gradeData.classId || (() => {
        const matchingClass = classes.find(cls => 
          cls.name === gradeData.className || cls.className === gradeData.className
        );
        return matchingClass?.id || matchingClass?.classId;
      })(),
      // 确保更新时间
      updatedAt: new Date().toISOString(),
      updatedBy: localStorage.getItem('currentUser') || 'system'
    };
    
    if (isEditing && selectedGrade) {
      // 编辑现有成绩记录
      setGrades(grades.map(g => 
        g.id === selectedGrade.id ? finalGradeData : g
      ));
    } else {
      // 添加新成绩记录
      setGrades([...grades, finalGradeData]);
    }
    setShowAddEditModal(false);
    setSelectedGrade(null);
    
    // 添加审计日志（如果系统支持）
    try {
      if (typeof addAuditLog === 'function') {
        addAuditLog({
          action: isEditing ? 'UPDATE_GRADE' : 'ADD_GRADE',
          entity: 'grade',
          entityId: finalGradeData.id,
          details: `${isEditing ? '更新' : '添加'}成绩记录: ${finalGradeData.studentName} - ${finalGradeData.subject}`
        });
      }
    } catch (error) {
      console.log('审计日志记录失败:', error);
    }
  };

  // 生成页码数组
  const generatePageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
    return pages;
  };

  // 计算统计数据
  const calculateStatistics = () => {
    if (filteredGrades.length === 0) {
      return {
        total: 0,
        average: 0,
        highest: 0,
        lowest: 0,
        passCount: 0,
        passRate: 0
      };
    }
    
    const scores = filteredGrades.map(g => g.score || 0);
    const total = scores.reduce((sum, score) => sum + score, 0);
    const average = Math.round(total / scores.length * 100) / 100;
    const highest = Math.max(...scores);
    const lowest = Math.min(...scores);
    const passCount = scores.filter(score => score >= 60).length;
    const passRate = Math.round((passCount / scores.length) * 100);
    
    return { total: filteredGrades.length, average, highest, lowest, passCount, passRate };
  };

  const stats = calculateStatistics();

  return (
    <div className="grade-management-container">
      <div className="page-header">
        <h1>成绩管理</h1>
        <div className="header-actions">
          <button className="add-grade-btn" onClick={handleAddGrade}>
            添加成绩记录
          </button>
        </div>
      </div>

      <div className="statistics-cards">
        <div className="stat-card">
          <div className="stat-value">{stats.total}</div>
          <div className="stat-label">总记录数</div>
        </div>
        <div className="stat-card average">
          <div className="stat-value">{stats.average}</div>
          <div className="stat-label">平均分</div>
        </div>
        <div className="stat-card highest">
          <div className="stat-value">{stats.highest}</div>
          <div className="stat-label">最高分</div>
        </div>
        <div className="stat-card lowest">
          <div className="stat-value">{stats.lowest}</div>
          <div className="stat-label">最低分</div>
        </div>
        <div className="stat-card pass-rate">
          <div className="stat-value">{stats.passRate}%</div>
          <div className="stat-label">及格率</div>
        </div>
      </div>

      <div className="filter-section">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索学生姓名或学号..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <div className="filter-controls">
          <select
            value={selectedTerm}
            onChange={(e) => setSelectedTerm(e.target.value)}
          >
            <option value="">所有学期</option>
            {termOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <select
            value={selectedExamType}
            onChange={(e) => setSelectedExamType(e.target.value)}
          >
            <option value="">所有考试类型</option>
            {examTypeOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <select
            value={selectedSubject}
            onChange={(e) => setSelectedSubject(e.target.value)}
          >
            <option value="">所有科目</option>
            {subjectOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grade-table-container">
        {/* 成绩表格 */}
        <div className="bg-white rounded-xl shadow-md overflow-hidden mb-6">
          <table className="grade-table min-w-full border-collapse">
            <thead className="bg-gradient-to-r from-blue-50 to-indigo-50 border-b-2 border-blue-100">
              <tr>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">学院</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">班级</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">教学周期</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">类型</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">导员</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">讲师</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">教学月度</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">课程</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 tracking-wide">总人数</th>
                <th className="px-6 py-4 text-center text-sm font-semibold text-gray-700 tracking-wide">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {currentGrades.length > 0 ? currentGrades.map((grade) => (
                <tr key={grade.id} className="hover:bg-blue-50 transition-colors duration-150">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-800">{grade.academy || '-'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.className || '-'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.term}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.examType}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.instructor || '-'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.lecturer || '-'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.teachingMonth || '-'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.subject}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-800">{grade.totalStudents || '-'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-center">
                    <div className="flex justify-center space-x-2">
                      <button
                        onClick={() => handleViewDetail(grade)}
                        className="px-3 py-1 text-xs font-medium text-blue-600 bg-blue-50 rounded hover:bg-blue-100 transition-colors duration-150"
                      >
                        查看
                      </button>
                      <button
                        onClick={() => handleEditGrade(grade)}
                        className="px-3 py-1 text-xs font-medium text-green-600 bg-green-50 rounded hover:bg-green-100 transition-colors duration-150"
                      >
                        编辑
                      </button>
                      <button
                        onClick={() => handleDeleteGrade(grade)}
                        className="px-3 py-1 text-xs font-medium text-red-600 bg-red-50 rounded hover:bg-red-100 transition-colors duration-150"
                      >
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
              )) : (
                <tr>
                  <td colSpan={10} className="px-6 py-12 text-center">
                    <div className="flex flex-col items-center justify-center text-gray-500">
                      <div className="text-4xl mb-2">📊</div>
                      <div className="text-lg font-medium">暂无成绩数据</div>
                      <div className="text-sm mt-1">请点击"添加成绩记录"按钮创建新的成绩数据</div>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div className="pagination-section">
        <div className="pagination-info">
          显示第 {indexOfFirstItem + 1} 到 {Math.min(indexOfLastItem, filteredGrades.length)} 条，共 {filteredGrades.length} 条记录
        </div>
        <div className="pagination-controls">
          <select
            value={itemsPerPage}
            onChange={handleItemsPerPageChange}
            className="items-per-page-select"
          >
            {itemsPerPageOptions.map(option => (
              <option key={option} value={option}>
                每页 {option} 条
              </option>
            ))}
          </select>
          <div className="page-buttons">
            <button
              onClick={goToFirstPage}
              disabled={currentPage === 1}
              className="page-btn"
            >
              首页
            </button>
            <button
              onClick={() => handlePageJump(currentPage - 1)}
              disabled={currentPage === 1}
              className="page-btn"
            >
              上一页
            </button>
            {generatePageNumbers().map(page => (
              <button
                key={page}
                onClick={() => handlePageJump(page)}
                className={`page-btn ${currentPage === page ? 'active' : ''}`}
              >
                {page}
              </button>
            ))}
            <button
              onClick={() => handlePageJump(currentPage + 1)}
              disabled={currentPage === totalPages}
              className="page-btn"
            >
              下一页
            </button>
            <button
              onClick={goToLastPage}
              disabled={currentPage === totalPages}
              className="page-btn"
            >
              末页
            </button>
          </div>
        </div>
      </div>

      {/* 添加/编辑成绩模态框 */}
      <AddEditGradeModal
        isOpen={showAddEditModal}
        onClose={() => setShowAddEditModal(false)}
        onSave={handleSaveGrade}
        initialData={selectedGrade}
        isEditing={isEditing}
        termOptions={termOptions}
        examTypeOptions={examTypeOptions}
        studentOptions={studentOptions}
        subjectOptions={subjectOptions}
        academyOptions={academyOptions}
        classOptions={classOptions}
        instructorOptions={instructorOptions}
        lecturerOptions={lecturerOptions}
        teachingMonthOptions={teachingMonthOptions}
        onClassChange={handleClassChange}
      />

      {/* 确认删除模态框 */}
      <ConfirmModal
        isOpen={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={confirmDeleteGrade}
        title="确认删除"
        message={`确定要删除 ${selectedGrade?.studentName} 的成绩记录吗？此操作不可撤销。`}
      />

      {/* 成绩详情模态框 */}
      <GradeDetailModal
        isOpen={showDetailModal}
        onClose={() => setShowDetailModal(false)}
        gradeData={selectedGrade}
      />
    </div>
  );
};

export default GradePage;